/*
 * @Author: 张仁会 28396543@qq.com
 * @Date: 2022-07-25 16:49:23
 * @LastEditors: 张仁会 28396543@qq.com
 * @LastEditTime: 2022-09-05 09:30:52
 * @FilePath: \exp-jwt\routes\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
var express = require('express');
var multer = require('multer');
var path = require('path');
var router = express.Router();

const fs = require('fs')
const formidable = require('formidable')
const sixLen = require('./utils/public.js')

// multer模块的初始化
var storage = multer.diskStorage({
  // 配置文件上传后存储的路径
  destination: function (req, file, cb) {
    // NodeJS的两个全局变量
    // console.log(__dirname);  //获取当前文件在服务器上的完整目录 
    // console.log(__filename); //获取当前文件在服务器上的完整路径 
    cb(null, path.join(__dirname, '../public/images/'))
  },
  // 配置文件上传后存储的路径和文件名
  filename: function (req, file, cb) {
    // console.log('file',file);
    req.body.imgUrl = Date.now() + path.extname(file.originalname)
    cb(null, Date.now() + path.extname(file.originalname))
  }
})

var upload = multer({ storage: storage })

// 获取用户
router.get('/getUser', async function (req, res, next) {
  let user = await global.query('select * from user')
  res.send({
    msg: '成功',
    code: 200,
    user
  });
});
// 修改用户
router.post('/setUser', async function (req, res, next) {
  let { id, username, password, remember } = req.body
  await global.query(`update user set username='${username}',password='${password}',remember=${remember} where id=${id}`)
  res.send({
    msg: '成功',
    code: 200,
  });
});
// 获取商品
router.get('/getStock', async function (req, res, next) {
  let stock = await global.query('select * from stock')
  res.send({
    msg: '成功',
    code: 200,
    stock
  });
});
// 修改商品
router.post('/setStock', async function (req, res, next) {
  let stock = await global.query('select * from stock')
  res.send({
    msg: '成功',
    code: 200,
    stock
  });
});
// 添加商品
router.post('/addStock', async function (req, res, next) {
  let stock = await global.query('select * from stock')
  res.send({
    msg: '成功',
    code: 200,
    stock
  });
});

// 图片上传 单个图片接收 upload.single('imgFile') upload.array('imgFile', 2)
router.post('/upload', upload.array('imgFile', 1), function (req, res, next) {
  console.log(req.body);
  res.send({ imgUrl: 'http://localhost:3000/images/' + req.body.imgUrl });
});

// 图片上传 单个图片接收 upload.single('imgFile') upload.array('imgFile', 2)
router.get('/download', function (req, res, next) {
  // res.send(path.join(__dirname, '../public/images/1648606396534.jpg'));
  // 下载静态资源的方法
  res.download(path.join(__dirname, '../public/images/1648606396534.jpg'))
});


// 大文件上传
const uploadFile = {}
router.post('/uploadAll', (req, res) => {
  const uploadDir = path.join(__dirname, '../public/images/')
  const form = new formidable.IncomingForm()
  form.parse(req, (err, fields, files) => {
    fs.readFile(files.file.path, (err, data) => {
      if (!uploadFile.hasOwnProperty(fields.filename)) {
        uploadFile[fields.filename] = {
          name: new Date().getTime() + '_' + sixLen(),
          index: []
        }
        fs.mkdir(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name, function () {
          console.log('创建文件夹成功')
        })//创建用于存储当前文件碎片的文件夹
      }
      const stream = fs.createWriteStream(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name + '/' + fields.cut + '.' + fields.type)
      stream.on('open', () => {
        stream.write(data);
        stream.end();
        uploadFile[fields.filename].index.push(fields.cut);

        console.log(uploadFile);
        let isDone = uploadFile[fields.filename].index.length == fields.total
        if (isDone) {//合并文件
          let result = uploadFile[fields.filename].index.sort((a, b) => a - b);
          let file = fs.createWriteStream(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name + '.' + fields.type);
          let index = 0
          file.on('open', () => {
            while (index < uploadFile[fields.filename].index.length) {
              let data = fs.readFileSync(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name + '/' + index + '.' + fields.type)
              file.write(data)
              fs.unlinkSync(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name + '/' + index + '.' + fields.type)
              index++
            }
            file.end()
            fs.rmdirSync(path.join(__dirname, '../public/images/') + uploadFile[fields.filename].name)
          })
        }
        res.json({
          code: 0,
          msg: '上传成功',
          // data: isDone ? ('http://localhost:3000/images/' + uploadFile[fields.filename].name + '.' + fields.type) : null,
          // isDone,
          uploadFile
        })
      })
    })
  })
})

module.exports = router;
